<template>
  <view class="write-diary-page">
    <!-- 页面标题 -->
    <view class="page-header">
      <text class="page-title">{{ isEditMode ? '编辑日记' : '写日记' }}</text>
      <text class="date-text">{{ diary.date }}</text>
    </view>
    
    <!-- 内容输入 -->
    <view class="content-section">
      <textarea 
        v-model="diary.content" 
        placeholder="今天发生了什么？记录下你的心情吧..."
        class="content-input"
        maxlength="500"
        @focus="onFocus"
        @blur="onBlur"
      ></textarea>
      <text :class="['char-count', { warning: diary.content.length > 400 }]">{{ diary.content.length }}/500</text>
    </view>
    
    <!-- 图片上传 -->
    <view class="img-upload-section">
      <text class="section-title">添加图片（最多3张）</text>
      <view class="img-upload">
        <view 
          class="upload-btn"
          v-if="diary.images.length < 3"
          @click="chooseImage"
        >
          <text class="upload-icon">+</text>
          <text class="upload-text">上传图片</text>
        </view>
        <view 
          v-for="(img, index) in diary.images" 
          :key="index" 
          class="img-wrapper"
          @click="previewImage(index)"
        >
          <image 
            :src="img" 
            class="preview-img"
            mode="aspectFill"
          ></image>
          <view class="delete-btn" @click.stop="deleteImage(index)">
            <text>×</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 标签选择 -->
    <view class="tag-section">
      <text class="section-title">心情标签</text>
      <view class="tag-select">
        <text 
          v-for="tag in tags" 
          :key="tag"
          :class="['tag-item', { active: diary.tag === tag }]"
          @click="diary.tag = tag"
        >
          <text class="tag-icon">{{ getTagIcon(tag) }}</text>
          <text>{{ tag }}</text>
        </text>
      </view>
    </view>

    <!-- 保存按钮 -->
    <button class="save-btn" @click="saveDiary" :disabled="!diary.content.trim()">
      <text class="save-icon">💾</text>
      保存日记
    </button>
  </view>
</template>

<script>
import { getStorage, setStorage } from '@/utils/storage'

export default {
  data() {
    return {
      diary: {
        id: '',
        content: '',
        images: [],
        tag: '日常',
        date: new Date().toLocaleDateString(),
        time: new Date().toLocaleTimeString(),
        fullTime: new Date().toISOString()
      },
      isEditMode: false,
      tags: ['开心', '疲惫', '学习', '日常', 'emo'],
      tagIcons: {
        '开心': '😄',
        '疲惫': '😴',
        '学习': '📚',
        '日常': '🌤️',
        'emo': '😔'
      },
      isFocused: false
    }
  },
  onLoad(options) {
    // 检查是否有id参数，判断是否为编辑模式
    if (options.id) {
      this.isEditMode = true
      this.loadDiaryForEdit(options.id)
    }
  },
  methods: {
    // 加载要编辑的日记数据
    loadDiaryForEdit(diaryId) {
      const diaryList = getStorage('DIARY') || []
      const diary = diaryList.find(item => item.id === diaryId)
      
      if (diary) {
        this.diary = diary
      } else {
        uni.showToast({
          title: '未找到该日记',
          icon: 'none',
          duration: 1500
        })
        // 返回上一页
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      }
    },
    // 获取标签图标
    getTagIcon(tag) {
      return this.tagIcons[tag] || '📌'
    },
    
    // 选择图片
    chooseImage() {
      uni.chooseImage({
        count: 3 - this.diary.images.length, // 最多选3张
        success: (res) => {
          this.diary.images = this.diary.images.concat(res.tempFilePaths)
          uni.showToast({
            title: '图片添加成功',
            icon: 'success',
            duration: 1000
          })
        }
      })
    },
    
    // 删除图片
    deleteImage(index) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这张图片吗？',
        success: (res) => {
          if (res.confirm) {
            this.diary.images.splice(index, 1)
          }
        }
      })
    },
    
    // 预览图片
    previewImage(index) {
      if (this.diary.images.length > 0) {
        uni.previewImage({
          urls: this.diary.images,
          current: index
        })
      }
    },
    
    // 保存日记
    saveDiary() {
      if (!this.diary.content.trim()) {
        uni.showToast({ 
          title: '内容不能为空哦~', 
          icon: 'none',
          duration: 1500
        })
        return
      }
      
      // 读取已有日记
      let diaryList = getStorage('DIARY') || []
      
      if (this.isEditMode) {
        // 编辑模式：更新已有日记
        const index = diaryList.findIndex(item => item.id === this.diary.id)
        if (index !== -1) {
          // 更新完整时间
          this.diary.fullTime = new Date().toISOString()
          diaryList[index] = this.diary
          
          // 按日期重新排序
          diaryList.sort((a, b) => new Date(b.fullTime) - new Date(a.fullTime))
          
          setStorage('DIARY', diaryList)
          
          // 跳转回日记列表
          uni.navigateBack()
          uni.showToast({ 
            title: '更新成功！', 
            icon: 'success',
            duration: 1500
          })
        }
      } else {
        // 新建模式：添加新日记
        const newDiary = {
          ...this.diary,
          id: Date.now().toString(),
          fullTime: new Date().toISOString()
        }
        diaryList.unshift(newDiary)
        setStorage('DIARY', diaryList)
        
        // 跳转回日记列表
        uni.navigateBack()
        uni.showToast({ 
          title: '保存成功！', 
          icon: 'success',
          duration: 1500
        })
      }
    },
    
    // 输入框获得焦点
    onFocus() {
      this.isFocused = true
    },
    
    // 输入框失去焦点
    onBlur() {
      this.isFocused = false
    }
  }
}
</script>

<style scoped>
.write-diary-page {
  padding: 20rpx;
  min-height: 100vh;
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
}

/* 页面标题 */
.page-header {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 25rpx;
  padding: 35rpx;
  margin-bottom: 25rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10rpx);
  display: flex;
  justify-content: space-between;
  align-items: center;
  animation: fadeInUp 0.5s ease;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.page-title {
  font-size: 38rpx;
  font-weight: bold;
  color: #333;
  letter-spacing: 2rpx;
}

.date-text {
  font-size: 26rpx;
  color: #fff;
  background: linear-gradient(135deg, #2196f3, #1976d2);
  padding: 10rpx 20rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 15rpx rgba(33, 150, 243, 0.3);
}

/* 内容输入 */
.content-section {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 25rpx;
  padding: 35rpx;
  margin-bottom: 25rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10rpx);
  position: relative;
  transition: all 0.3s ease;
  animation: fadeInUp 0.5s ease 0.1s both;
}

.content-section:focus-within {
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.15);
  transform: translateY(-2rpx);
}

.content-input {
  width: 100%;
  min-height: 350rpx;
  padding: 0;
  margin: 0;
  border: none;
  outline: none;
  font-size: 28rpx;
  color: #333;
  line-height: 1.8;
  resize: vertical;
  background: transparent;
  font-family: inherit;
  transition: all 0.3s ease;
}

.content-input::placeholder {
  color: #ccc;
  font-style: italic;
  font-size: 28rpx;
  transition: all 0.3s ease;
}

.content-input:focus::placeholder {
  color: #999;
  transform: translateY(-5rpx);
}

.char-count {
  position: absolute;
  bottom: 25rpx;
  right: 35rpx;
  font-size: 24rpx;
  color: #999;
  transition: all 0.3s ease;
  font-weight: 500;
}

.char-count.warning {
  color: #f5576c;
  font-weight: bold;
}

.char-count.warning ~ .content-input {
  color: #f5576c;
}

/* 图片上传 */
.img-upload-section {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 25rpx;
  padding: 35rpx;
  margin-bottom: 25rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10rpx);
  animation: fadeInUp 0.5s ease 0.2s both;
}

.section-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 25rpx;
  display: block;
  letter-spacing: 1rpx;
}

.img-upload {
  display: flex;
  flex-wrap: wrap;
  gap: 25rpx;
}

.upload-btn {
  width: 160rpx;
  height: 160rpx;
  border: 3rpx dashed rgba(33, 150, 243, 0.5);
  border-radius: 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(33, 150, 243, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.upload-btn::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: linear-gradient(45deg, transparent, rgba(33, 150, 243, 0.2), transparent);
  transform: rotate(45deg);
  transition: all 0.6s ease;
}

.upload-btn:hover::before {
  left: 100%;
}

.upload-btn:hover {
  border-color: rgba(33, 150, 243, 0.8);
  background: rgba(33, 150, 243, 0.15);
  transform: translateY(-3rpx);
}

.upload-btn:active {
  transform: scale(0.95) translateY(-3rpx);
  border-color: rgba(33, 150, 243, 1);
}

.upload-icon {
  font-size: 45rpx;
  color: #2196f3;
  margin-bottom: 12rpx;
  position: relative;
  z-index: 1;
  font-weight: bold;
}

.upload-text {
  font-size: 24rpx;
  color: #2196f3;
  position: relative;
  z-index: 1;
  font-weight: 500;
}

.img-wrapper {
  position: relative;
  width: 160rpx;
  height: 160rpx;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 15rpx rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
  cursor: pointer;
  animation: fadeIn 0.5s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: scale(0.8);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

.img-wrapper:hover {
  transform: scale(1.05) translateY(-3rpx);
  box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.2);
}

.preview-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: all 0.3s ease;
}

.img-wrapper:hover .preview-img {
  transform: scale(1.1);
}

.delete-btn {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
  width: 45rpx;
  height: 45rpx;
  background: rgba(0, 0, 0, 0.7);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 32rpx;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.3);
  z-index: 2;
  opacity: 0.8;
}

.delete-btn:hover {
  transform: scale(1.2);
  background: rgba(255, 0, 0, 0.9);
  opacity: 1;
}

.delete-btn:active {
  transform: scale(1.1);
}

/* 标签选择 */
.tag-section {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 25rpx;
  padding: 35rpx;
  margin-bottom: 40rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10rpx);
  animation: fadeInUp 0.5s ease 0.3s both;
}

.tag-select {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.tag-item {
  display: flex;
  align-items: center;
  gap: 10rpx;
  padding: 18rpx 30rpx;
  border-radius: 35rpx;
  font-size: 26rpx;
  color: #666;
  background: rgba(173, 216, 230, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
  border: 2rpx solid transparent;
}

.tag-item:hover {
  background: rgba(173, 216, 230, 0.2);
  transform: translateY(-3rpx);
}

.tag-item:active {
  transform: scale(0.95) translateY(0);
}

.tag-item.active {
  background: linear-gradient(135deg, #2196f3, #1976d2);
  color: white;
  box-shadow: 0 6rpx 20rpx rgba(33, 150, 243, 0.4);
  border-color: rgba(255, 255, 255, 0.3);
  transform: translateY(-3rpx);
}

.tag-icon {
  font-size: 32rpx;
  transition: transform 0.3s ease;
}

.tag-item.active .tag-icon {
  transform: scale(1.2);
}

/* 保存按钮 */
.save-btn {
  background: linear-gradient(135deg, #2196f3, #1976d2);
  color: white;
  border-radius: 55rpx;
  font-size: 32rpx;
  font-weight: bold;
  padding: 25rpx;
  border: none;
  outline: none;
  box-shadow: 0 8rpx 35rpx rgba(33, 150, 243, 0.5);
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 15rpx;
  cursor: pointer;
  animation: fadeInUp 0.5s ease 0.4s both;
  letter-spacing: 2rpx;
}

.save-btn:hover:not(:disabled) {
  transform: translateY(-3rpx);
  box-shadow: 0 12rpx 45rpx rgba(33, 150, 243, 0.6);
}

.save-btn:active:not(:disabled) {
  transform: scale(0.98) translateY(0);
  box-shadow: 0 6rpx 25rpx rgba(33, 150, 243, 0.4);
}

.save-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
  box-shadow: 0 4rpx 20rpx rgba(33, 150, 243, 0.2);
}

.save-icon {
  font-size: 36rpx;
  transition: transform 0.3s ease;
}

.save-btn:active:not(:disabled) .save-icon {
  transform: rotate(30deg);
}
</style>